package org.linlinjava.litemall.db.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.linlinjava.litemall.db.config.RedisConfig;
import org.linlinjava.litemall.db.core.RedisCache;
import org.linlinjava.litemall.db.domain.SysConfig;
import org.linlinjava.litemall.db.dao.SysConfigMapper;
import org.linlinjava.litemall.db.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.xml.crypto.Data;
import java.util.*;

@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {

    @Autowired
    private RedisCache redisCache;
    @Override
    public SysConfig selectSysConfiById(Long id) {
        return getById(id);
    }



    /**
     * 查询系统配置列表
     *
     * @param sysConfi 系统配置
     * @return 系统配置
     */
    @Override
    public List<SysConfig> selectSysConfiList(SysConfig sysConfi)
    {
        return baseMapper.selectSysConfiList(sysConfi);
    }

    /**
     * 新增系统配置
     *
     * @param sysConfi 系统配置
     * @return 结果
     */
    @Override
    public int insertSysConfi(SysConfig sysConfi)
    {
        sysConfi.setCreateTime(new Date());
        return baseMapper.insert(sysConfi);
    }

    /**
     * 修改系统配置
     *
     * @param sysConfi 系统配置
     * @return 结果
     */
    @Override
    public int updateSysConfi(SysConfig sysConfi)
    {
        sysConfi.setUpdateTime(new Date());
        return baseMapper.updateById(sysConfi);
    }

    /**
     * 批量删除系统配置
     *
     * @param ids 需要删除的系统配置主键
     * @return 结果
     */
    @Override
    public int deleteSysConfiByIds(Long[] ids)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除系统配置信息
     *
     * @param id 系统配置主键
     * @return 结果
     */
    @Override
    public int deleteSysConfiById(Long id)
    {
        return baseMapper.deleteById(id);
    }


    @PostConstruct
    public void init()
    {
        List<SysConfig> sysConfigList = baseMapper.selectList(null);
        Map<String, String> configCache = new HashMap<>();
        for (SysConfig sysConfig : sysConfigList) {
            configCache.put(sysConfig.getConfigKey(), sysConfig.getConfigValue());
        }
        redisCache.setCacheMap("sys_config", configCache);
    }
}
